package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CancelOrderContext_X;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.StockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author XuBang
 * @TODO:
 * （3）根据商品id,将tb_stock中“冻结库存数量lock_count”归还给“库存数量stock_count”
 * @date 2021/11/2
 * @trainOfthought:
 */
@Component
@Transactional
public class BackStockHandler extends AbstractTransHandler {

    //1.注入数据库对应的mapper
    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    /**
     * 使用stockMapper,将tb_stock中“冻结库存数量lock_count”归还给“库存数量stock_count”
     * @param context
     * @return
     */
    @Override
    public boolean handle(TransHandlerContext context) {
        CancelOrderContext_X cancelOrderContext_x = new CancelOrderContext_X();
        List<OrderItem> orderItems = cancelOrderContext_x.getOrderItems();  //获取多个订单商品关联表
        for (OrderItem orderItem : orderItems) {  //逐个从商品关联表单条数据，获取订单id
            Stock stock = new Stock();
            stock.setItemId(orderItem.getItemId());  //赋值商品id
            stock.setLockCount(-orderItem.getNum());
            stock.setStockCount(orderItem.getNum().longValue());   //内部对该数据进行求和
            Integer cnt = stockMapper.updateStock(stock);
            if(cnt==0) {
                throw new BizException("库存返回出错！");
            }
        }
        return true;
    }
}
